/**
 * Copyright (c) 2018 苍穹跃龙
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.l.core.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;

import com.baomidou.mybatisplus.plugins.Page;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @author 严秋旺
 * @date 2018-09-23
 */
@Data
@Accessors(chain = true)
public class RestJson {
    private Integer code;
    private String message;
    private Map<String, Object> data;
    private List<FormError> errors;
    /**
     * 分页使用
     */
    private Long total;
    private List<?> rows;

    public RestJson() {
    }

    public RestJson(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public RestJson(RestCode apiCode) {
        this.code = apiCode.getCode();
        this.message = apiCode.getMessage();
    }

    public RestJson(RestCode apiCode, Errors errors) {
        this(apiCode);
        this.addErrors(errors);
    }

    public RestJson addErrors(Errors errors) {
        List<FieldError> fieldErrors = errors.getFieldErrors();

        if (this.errors == null) {
            this.errors = new ArrayList<>();
        }

        fieldErrors.forEach(e -> {
            FormError formError = new FormError();
            formError.setName(e.getField());
            formError.setMessage(e.getDefaultMessage());
            System.out.println(e.getCode());
            System.out.println(e.getCodes());
            this.errors.add(formError);
        });
        return this;
    }

    public RestJson put(String key, Object value) {
        if (data == null) {
            data = new HashMap<>();
        }

        data.put(key, value);
        return this;
    }

    public boolean isSuccess() {
        return this.code == RestCode.SUCCESS.getCode();
    }

    public static RestJson Success() {
        return new RestJson(RestCode.SUCCESS);
    }

    public static RestJson Failed() {
        return new RestJson(RestCode.FAILED);
    }

    public RestJson page(Page<?> page) {
        this.total = page.getTotal();
        this.rows = page.getRecords();
        return this;
    }

}
